<?php

if (!defined('BASEPATH'))
        exit('No direct script access allowed');
	
	

/**
 * ------------------------------------------------------------------------------------
 * Base Model
 * ------------------------------------------------------------------------------------
 *
 * @info every model must extends from Base Model
 *
 * @property CI_DB_forge $dbforge                 Database Utility Class
 * @property CI_Benchmark $benchmark              This class enables you to mark points and calculate the time difference between them.<br />  Memory consumption can also be displayed.
 * @property CI_Calendar $calendar                This class enables the creation of calendars
 * @property CI_Cart $cart                        Shopping Cart Class
 * @property CI_Config $config                    This class contains functions that enable config files to be managed
 * @property CI_Controller $controller            This class object is the super class that every library in.<br />CodeIgniter will be assigned to.
 * @property CI_Email $email                      Permits email to be sent using Mail, Sendmail, or SMTP.
 * @property CI_Encrypt $encrypt                  Provides two-way keyed encoding using XOR Hashing and Mcrypt
 * @property CI_Exceptions $exceptions            Exceptions Class
 * @property CI_Form_validation $form_validation  Form Validation Class
 * @property CI_Ftp $ftp                          FTP Class
 * @property CI_Hooks $hooks                      //dead
 * @property CI_Image_lib $image_lib              Image Manipulation class
 * @property CI_Input $input                      Pre-processes global input data for security
 * @property CI_Lang $lang                        Language Class
 * @property CI_Loader $load                      Loads views and files
 * @property CI_Log $log                          Logging Class
 * @property CI_Model $model                      CodeIgniter Model Class
 * @property CI_Output $output                    Responsible for sending final output to browser
 * @property CI_Pagination $pagination            Pagination Class
 * @property CI_Parser $parser                    Parses pseudo-variables contained in the specified template view,<br />replacing them with the data in the second param
 * @property CI_Profiler $profiler                This class enables you to display benchmark, query, and other data<br />in order to help with debugging and optimization.
 * @property CI_Router $router                    Parses URIs and determines routing
 * @property CI_Session $session                  Session Class
 * @property CI_Table $table                      HTML table generation<br />Lets you create tables manually or from database result objects, or arrays.
 * @property CI_Trackback $trackback              Trackback Sending/Receiving Class
 * @property CI_Typography $typography            Typography Class
 * @property CI_Unit_test $unit_test              Simple testing class
 * @property CI_Upload $upload                    File Uploading Class
 * @property CI_URI $uri                          Parses URIs and determines routing
 * @property CI_User_agent $user_agent            Identifies the platform, browser, robot, or mobile devise of the browsing agent
 * @property CI_Xmlrpc $xmlrpc                    XML-RPC request handler class
 * @property CI_Xmlrpcs $xmlrpcs                  XML-RPC server class
 * @property CI_Zip $zip                          Zip Compression Class
 * @property CI_Javascript $javascript            Javascript Class
 * @property CI_Jquery $jquery                    Jquery Class
 * @property CI_Utf8 $utf8                        Provides support for UTF-8 environments
 * @property CI_Security $security                Security Class, xss, csrf, etc...
 * @property CI_Driver_Library $driver            CodeIgniter Driver Library Class
 * @property CI_Cache $cache                      CodeIgniter Caching Class
 * @property MG $mg                               MongoDB Library
 *
 * @author lanlin
 * @change 2016-04-09
 */
class Base_Model extends CI_Model
{

    //----------------------------------------------------------------------------------
    private $_table = "";

    /**
     * Base_Model Construct
     */
    public function __construct($table = "")
    {
        $this->_table = $table;
        parent::__construct();
        $this->load->database();
    }

    /**
     * 通用过滤器
     */
    private function _filter(&$map)
    {
    
    }

    /**
     * 数据列表
     */
    public function get_list($where = "", $filed = "", $orwhere = "", $inwhere = "", $notwhere = "", $like = array())
    {
        if (empty($where)) {
            $this->_filter($where);
        }
        //获取当前页
        $pageCurrent = $this->input->post("pageCurrent") ? $this->input->post("pageCurrent") : 1;
        //每页显示数量
        $pageSize = $this->input->post("pageSize") ? $this->input->post("pageSize") : 30;
        //排序字段
        $orderField = $this->input->post("orderField") ? $this->input->post("orderField") : "id";
        //排序方式
        $orderDirection = $this->input->post("orderDirection") ? $this->input->post("orderDirection") : "desc";
        //获取总数
        $total = $this->count($where);
        //分页
        $limit = ($pageCurrent - 1) * $pageSize;
        //排序方式
        $order = $orderField . " " . $orderDirection;
        //数据
        $list = $this->search($where, $filed, $limit, $pageSize, $order, $orwhere, $inwhere, $notwhere, $like);
        //封装
        $return = array(
            'total' => $total,
            'pageCurrent' => $pageCurrent,
            'pageSize' => $pageSize,
            'orderField' => $orderField,
            "orderDirection" => $orderDirection,
            "list" => $list
        );
        return $return;
    }
/*
 *  authod   zhipingwu
 */
    public function get_list_ping($where = "", $filed = "", $orwhere = "", $inwhere = "", $notwhere = "", $like = array(),$orderField = array())
    {
        //获取当前页
        $pageCurrent = $this->input->get_post("pageCurrent") ? $this->input->get_post("pageCurrent") : 1;
        //每页显示数量
        $pageSize = $this->input->get_post("pageSize") ? $this->input->get_post("pageSize") : 30;
        //排序字段
        if($orderField == false){
            $orderField = $this->input->get_post("orderField") ? $this->input->get_post("orderField") : "id";
        }
        if (!empty($like) && is_array($like)) {
            foreach ($like as $ik => $iv) {
                $this->db->like($ik, $iv);
            }
        }
        //排序方
        $orderDirection = $this->input->get_post("orderDirection") ? $this->input->get_post("orderDirection") : "desc";
        //获取总数
        $total = $this->count($where);
        //分页
        $limit = ($pageCurrent - 1) * $pageSize;
        //排序方式
        $order = $orderField . " " . $orderDirection;
        //数据
        $list = $this->search($where, $filed, $limit, $pageSize, $order, $orwhere, $inwhere, $notwhere, $like);
        //封装
        $return = array(
            'total' => $total,
            'pageCurrent' => $pageCurrent,
            'pageSize' => $pageSize,
            'orderField' => $orderField,
            "orderDirection" => $orderDirection,
            "list" => $list
        );
        return $return;
    }


    /**
     * 公共搜索方法
     */
    public function search($where = "", $filed = "", $limit = "", $offset = "", $order = "", $orwhere = "", $inwhere = "", $notwhere = "", $like = array(),$group_by = "")
    {
        if (!empty($where) && is_array($where)) {
            $this->db->where($where);
        }
        if (!empty($orwhere) && is_array($orwhere)) {
            $this->db->or_where($orwhere);
        }
        if (!empty($inwhere) && is_array($inwhere)) {
            foreach ($inwhere as $ik => $iv) {
                $this->db->where_in($ik, $iv);
            }
        }
        if (!empty($notwhere) && is_array($notwhere)) {
            foreach ($notwhere as $ik => $iv) {
                $this->db->where_not_in($ik, $iv);
            }
        }
		 if ($group_by) {
            $this->db->group_by($group_by);
        }
        if ($filed) {
            $this->db->select($filed);
        }
        if (!empty($order)) {
            $this->db->order_by($order);
        }else{
        	$this->db->order_by("id DESC");
        }
        if ($limit) {
            $this->db->limit($limit, $offset);
        }

        if (!empty($like) && is_array($like)) {
            foreach ($like as $ik => $iv) {
                $this->db->like($ik, $iv);
            }
        }
        $query = $this->db->get($this->_table)->result_array();
        return $query;
    }

    /**
     * 保存数据
     */
    public function create($data = array(), $batch = FALSE)
    {

        if ($batch) {
            $query = $this->db->insert_batch($this->_table, $data);
        } else {
            $query = $this->db->insert($this->_table, $data);
        }
        return $query;
    }

    /**
     * 更新数据
     */
    public function update($data = array(), $where = "", $batch = FALSE, $orwhere = "", $inwhere = "", $notwhere = "", $like = array())
    {
        if (!empty($where) && is_array($where)) {
            $this->db->where($where);
        }
        if (!empty($orwhere) && is_array($orwhere)) {
            $this->db->or_where($orwhere);
        }
        if (!empty($inwhere) && is_array($inwhere)) {
            foreach ($inwhere as $ik => $iv) {
                $this->db->where_in($ik, $iv);
            }
        }
        if (!empty($notwhere) && is_array($notwhere)) {
            foreach ($notwhere as $ik => $iv) {
                $this->db->where_not_in($ik, $iv);
            }
        }
        if ($batch) {
            $query = $this->db->update_batch($this->get_table(), $data);
        } else {
            $query = $this->db->update($this->_table, $data);
        }
        return $this->db->affected_rows();
    }

    /**
     * 读取数据
     * @param type $table
     * @param type $where
     * @return type
     */
    public function read($where = array(), $order_by = "", $like_where = array(), $filed = "")
    {
        if ($like_where) {
            foreach ($like_where as $key => $v) {
                if ($v) {
                    $this->db->like($key, $v);
                    unset($like_where[$key]);
                }
            }
        }
        if ($filed) {
            $this->db->select($filed);
        }
        if (!empty($where) && is_array($where)) {
            $this->db->where($where);
        }
        if ($order_by) {
            $this->db->order_by($order_by);
        }
        
        return $this->db->get($this->_table)->row_array();
    }

    /**
     * 删除数据
     * @param type $table
     * @param type $where
     */
    public function delete($where = "", $orwhere = "", $inwhere = "", $notwhere = "", $like = array())
    {
        if (!empty($where) && is_array($where)) {
            $this->db->where($where);
        }
        if (!empty($orwhere) && is_array($orwhere)) {
            $this->db->or_where($orwhere);
        }
        if (!empty($inwhere) && is_array($inwhere)) {
            foreach ($inwhere as $ik => $iv) {
                $this->db->where_in($ik, $iv);
            }
        }
        if (!empty($notwhere) && is_array($notwhere)) {
            foreach ($notwhere as $ik => $iv) {
                $this->db->where_not_in($ik, $iv);
            }
        }

        if (!empty($like) && is_array($like)) {
            foreach ($like as $ik => $iv) {
                $this->db->like($ik, $iv);
            }
        }
        return $this->db->delete($this->_table);
    }

    /**
     * 获取总数
     */
    public function count($where = "", $orwhere = "", $inwhere = "", $notwhere = "", $like = array())
    {
        if (!empty($where) && is_array($where)) {
            $this->db->where($where);
        }
        if (!empty($orwhere) && is_array($orwhere)) {
            $this->db->or_where($orwhere);
        }
        if (!empty($inwhere) && is_array($inwhere)) {
            foreach ($inwhere as $ik => $iv) {
                $this->db->where_in($ik, $iv);
            }
        }
        if (!empty($notwhere) && is_array($notwhere)) {
            foreach ($notwhere as $ik => $iv) {
                $this->db->where_not_in($ik, $iv);
            }
        }

        if (!empty($like) && is_array($like)) {
            foreach ($like as $ik => $iv) {
                $this->db->like($ik, $iv);
            }
        }
        return $this->db->count_all_results($this->_table);
    }

    // ------------------------------------------------------------------------------
    /**
     * insert last id
     *
     */
    public function get_insert_id()
    {

        return $this->db->insert_id();
    }

    /**
     * left查询
     */
    public function get_left_join_list($table_nane = "", $left_join_on = "", $where = "", $filds = "*", $order = "", $notwhere = "", $inwhere = "", $limit = NULL, $offset = NULL, $group_by = NULL,$like=array())
    {
    	$this->db->select($filds);
        if (!empty($order)) {
            $this->db->order_by($order);
        }

        if (!empty($notwhere) && is_array($notwhere)) {
            foreach ($notwhere as $ik => $iv) {
                $this->db->where_not_in($ik, $iv);
            }
        }
        if (!empty($inwhere) && is_array($inwhere)) {
            foreach ($inwhere as $ik => $iv) {
                $this->db->where_in($ik, $iv);
            }
        }
        if ($limit) {
            $this->db->limit($limit, $offset);
        }
        if ($group_by) {
            $this->db->group_by($group_by);
        }
        if (!empty($like) && is_array($like)) {
            foreach ($like as $ik => $iv) {
                $this->db->like($ik, $iv);
            }
        }
      
        $this->db->from($this->_table);
        $this->db->join($table_nane, $left_join_on, 'LEFT');
        $this->db->where($where);
        return $this->db->get()->result_array();
    }
 /**
     * left查询
     */
    public function get_left_join_list_count($table_nane = "", $left_join_on = "", $where = "", $filds = "*", $order = "", $notwhere = "", $inwhere = "", $group_by = NULL,$like = array())
    {
    	$this->db->select($filds);
        if (!empty($order)) {
            $this->db->order_by($order);
        }

        if (!empty($notwhere) && is_array($notwhere)) {
            foreach ($notwhere as $ik => $iv) {
                $this->db->where_not_in($ik, $iv);
            }
        }
        if (!empty($inwhere) && is_array($inwhere)) {
            foreach ($inwhere as $ik => $iv) {
                $this->db->where_in($ik, $iv);
            }
        }
        if ($group_by) {
            $this->db->group_by($group_by);
        }
        if (!empty($like) && is_array($like)) {
        	foreach ($like as $ik => $iv) {
        		$this->db->like($ik, $iv);
        	}
        }
        $this->db->from($this->_table);
        $this->db->join($table_nane, $left_join_on, 'LEFT');
        $this->db->where($where);
        $list = $this->db->get()->result_array();
		return count($list);
    }
	
	/**
     * 数据列表分页
     */
    public function get_left_join_list_page($list)
    {
        if (empty($where)) {
            $this->_filter($where);
        }
        //获取当前页
        $pageCurrent = $this->input->get_post("pageCurrent") ? $this->input->get_post("pageCurrent") : 1;
        //每页显示数量
        $pageSize = $this->input->get_post("pageSize") ? $this->input->get_post("pageSize") : 30;
        //排序字段
        $orderField = $this->input->get_post("orderField") ? $this->input->get_post("orderField") : "id";
        //排序方式
        $orderDirection = $this->input->get_post("orderDirection") ? $this->input->get_post("orderDirection") : "";
        //分页
        $page_start = ($pageCurrent - 1) * $pageSize;
        //排序方式
		 $order_str = "";
		 if($orderField && $orderDirection){
			 $order_str = $orderField . " " . $orderDirection;
		 }
        $order_arr = isset($list['order']) && $list['order'] ? $list['order'] : "";
		
        //数据
		$table_nane = $list['table_nane'];
		$left_join_on = $list['left_join_on'];
		$where = isset($list['where']) && $list['where'] ? $list['where'] : "";
		$filds = isset($list['filds']) && $list['filds'] ? $list['filds'] : "*";
		$order = $order_str ? $order_str : $order_arr;
		$notwhere = isset($list['notwhere']) && $list['notwhere'] ? $list['notwhere'] : "";
		$inwhere = isset($list['inwhere']) && $list['inwhere'] ? $list['inwhere'] : "";
		$limit = $pageSize;
		$offset = $page_start;
		$group_by = isset($list['group_by']) && $list['group_by'] ? $list['group_by'] : "";
		$like = isset($list['like']) && $list['like'] ? $list['like'] : "";
        $list = $this->get_left_join_list($table_nane, $left_join_on, $where, $filds, $order, $notwhere, $inwhere, $limit, $offset, $group_by,$like);
		 //获取总数
        $total = $this->get_left_join_list_count($table_nane, $left_join_on, $where, $filds, $order, $notwhere, $inwhere, $group_by,$like);
        //封装
        $return = array(
            'total' => $total,
            'pageCurrent' => $pageCurrent,
            'pageSize' => $pageSize,
            'orderField' => $orderField,
            "orderDirection" => $orderDirection,
            "list" => $list
        );
        return $return;
    }
	
  
}
